from PySide6.QtCore import QObject, Signal
from loguru import logger
from ..models.margin_trading_model import MarginTradingModel


class MarginTradingController(QObject):
    
    data_loaded = Signal(dict)  # 发送所有图表数据
    loading_state_changed = Signal(bool)  # is_loading
    
    def __init__(self):
        super().__init__()
        self.model = MarginTradingModel()

    def get_default_date_range(self):
        return self.model.get_default_date_range()

    def load_chart_data(self, start_date: str, end_date: str):
        self.loading_state_changed.emit(True)
        
        try:
            # 获取数据
            df = self.model.get_margin_trading_data(start_date, end_date)
            
            if df is not None and not df.empty:
                chart_data = self._process_chart_data(df, start_date, end_date)
                self.data_loaded.emit(chart_data)
                logger.info(f"成功加载融资融券数据，共 {len(df)} 条记录")
            else:
                logger.warning("未获取到融资融券数据")
                self.data_loaded.emit({})
                
        except Exception as e:
            logger.exception(f"获取融资融券数据时出错: {e}")
            self.data_loaded.emit({})
        finally:
            self.loading_state_changed.emit(False)

    def _process_chart_data(self, df, start_date: str, end_date: str) -> dict:
        """处理所有图表数据"""
        chart_data = {
            'financing_ratio': None,
            'financing_balance': [],
            'financing_buy': [],
            'sec_value': [],
            'sec_sell': []
        }
        
        # 处理融资买入比例数据
        market_volume_df = self.model.get_total_market_volume(start_date, end_date)
        if not market_volume_df.empty:
            ratio_df = self.model.calculate_financing_ratio(df, market_volume_df)
            if not ratio_df.empty:
                percentile_data = self.model.calculate_percentile_rank(
                    ratio_df['financing_ratio'].values, window=250
                )
                
                chart_data['financing_ratio'] = {
                    'dates': ratio_df['date'].tolist(),
                    'ratios': ratio_df['financing_ratio'].tolist(),
                    'percentiles': percentile_data
                }
                logger.info(f"成功计算融资买入比例数据，共 {len(ratio_df)} 条记录")
            else:
                logger.warning("未能计算融资买入比例数据")
        else:
            logger.warning("未获取到全市场成交额数据，无法计算融资买入比例")

        # 处理各交易所数据
        exchange_config = self.model.get_exchange_configs()
        exchanges = exchange_config['exchanges']
        colors = exchange_config['colors']
        names = exchange_config['names']

        fields = ['financing_balance', 'financing_buy_amount', 'securities_lending_balance', 'securities_lending_sell_volume']
        chart_keys = ['financing_balance', 'financing_buy', 'sec_value', 'sec_sell']
        
        for field, chart_key in zip(fields, chart_keys):
            for exchange, color, name in zip(exchanges, colors, names):
                daily_data = self.model.process_exchange_data(df, exchange, field)
                if len(daily_data) > 0:
                    chart_data[chart_key].append({
                        'dates': daily_data['date'],
                        'values': daily_data[field],
                        'name': name,
                        'color': color
                    })

        return chart_data